package logiclib

import (
	"strings"
)

//RPCServerStart RPC服务器启动
func RPCServerStart(processes []*ProcessBase, isDaemon *bool) {
	if GetCommandCallbackHandle == nil {
		GetCommandCallbackHandle = func(name *string, cmd *CMDStruct) {
			//println("Command call:" + *name)
			if cmd != nil {
				tempCmd := LockByName(*name, true)
				println("STOP:" + *name)
				cmd.Command = tempCmd
				cmd.Name = *name
				cmd.Param = ""
			}
			return
		}
	}
	if GetInfoCallbackHandle == nil {
		GetInfoCallbackHandle = func(cmd *CMDStruct, res *ResponseStruct) {
			if cmd != nil {
				switch strings.ToUpper(cmd.Command) {
				case "STOP":
					if strings.ToUpper(cmd.Name) == "ALL" {
						if UnLockAll("STOP") {
							res.Name = cmd.Name
							res.Response = "STOP"
							res.Result = "OK"
						} else {
							res.Name = cmd.Name
							res.Response = "STOP"
							res.Result = "FAILED"
						}
					} else if strings.ToUpper(cmd.Name) == "DAEMON" {
						res.Name = cmd.Name
						res.Response = "STOP"
						res.Result = "OK"
					} else {
						if UnLockByName(cmd.Name, "STOP") {
							res.Name = cmd.Name
							res.Response = "STOP"
							res.Result = "OK"
						} else {
							res.Name = cmd.Name
							res.Response = "STOP"
							res.Result = "FAILED"
						}
						break
					}
				case "START":
					if strings.ToUpper(cmd.Name) == "ALL" {
						for _, p := range processes {
							p.Start()
							go p.Wait()
							res.Name = cmd.Name
							res.Response = "START"
							res.Result = "OK"
						}
					} else if strings.ToUpper(cmd.Name) == "DAEMON" {
						res.Name = cmd.Name
						res.Response = "START"
						res.Result = "OK"
					} else {
						for _, p := range processes {
							if p.GetTitle() == cmd.Name {
								p.Start()
								go p.Wait()
								res.Name = cmd.Name
								res.Response = "START"
								res.Result = "OK"
								break
							}
						}
					}
					break
				case "STATUES":
					if strings.ToUpper(cmd.Name) == "DAEMON" {
						res.Name = "DAEMON"
						res.Response = "Stoped"
						if *isDaemon {
							res.Response = "Running"
						}
						res.Result = "OK"
						break
					}
					for _, p := range processes {
						if p.GetTitle() == cmd.Name {
							res.Name = cmd.Name
							res.Response = p.GetRunningStatue()
							res.Result = "OK"
							break
						}
					}
					break
				case "DAEMON":
					ctl := strings.ToUpper(cmd.Param) == "TRUE"
					for _, p := range processes {
						p.SetIsDaemon(ctl)
						res.Name = cmd.Name
						res.Response = "OK"
						res.Result = "OK"
					}
					*isDaemon = ctl
					break
				default:
					println("Info call error:" + cmd.Name)
					println(cmd.Command)
					println(cmd.Param)
					break
				}
			}
			return
		}
	}
	server := new(RPCServerManager)
	server.Start()
}
